﻿using Microsoft.Extensions.Options;
using Qy.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class NoticeKeyService : QyRepository<NoticeKey>
{
    private readonly NoticeService _noticeService;
    public NoticeKeyService(NoticeService noticeService, ApplicationContext applicationContext) : base(applicationContext)
    {
        _noticeService = noticeService;
    }

    public async Task<ViewNotice> GetAndUserAsync(int id)
    {
        return await Queryable()
            .LeftJoin<Notice>((key, notice) => key.Nid == notice.Id)
            .LeftJoin<User>((key, notice, getUser) => key.GetUid == getUser.Id)
            .LeftJoin<User>((key, notice, getUser, postUser) => notice.PostUid == postUser.Id)
            .Where((key, notice) => notice.Id == id)
            .Select((key, notice, getUser, postUser) => new ViewNotice()
            {
                Id = key.Id.SelectAll(),
                GetNickname = getUser.NickName,
                GetUserAvatar = getUser.Avatar,
                PostNickname = postUser.NickName,
                PostAvatar = postUser.Avatar,
                Title = notice.Title,
                Type = notice.Type,
                Content = notice.Content,
                PostUid = notice.PostUid,
                PostTime = notice.PostTime,
                NoticeId = notice.Id,
                Att = notice.Att
            })
            .FirstAsync();
    }

    /// <summary>
    /// 读取一条
    /// </summary>
    /// <param name="id"></param>
    /// <param name="userInfo"></param>
    /// <returns></returns>
    public virtual async Task<ViewNotice> ReadAsync(int id, int uid)
    {
        NoticeKey noticeKey = await GetIdAsync(id);
        ViewNotice notice = await GetAndUserAsync(noticeKey.Nid);
        if (uid != notice.PostUid && noticeKey.Status != 1)
        {
            noticeKey.Status = 1;
            noticeKey.ReadTime = DateTime.Now;
            await UpdateAsync(noticeKey);
        }
        return notice;
    }
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="noticeId"></param>
    /// <returns></returns>
    public virtual async Task<ViewNotice> ReadOneAsync(int noticeId)
    {
        return await GetAndUserAsync(noticeId);
    }

    public async Task<long> CountAsync(int uid)
    {
        return await Queryable().Where(data => data.Status == 0 && data.GetUid == uid).CountAsync();
    }

    public async Task<PagedInfo<ViewNotice>> GetPageListAsync(NoticeQuery parm)
    {
        var exp = Expressionable.Create<NoticeKey>();
        exp = exp.AndIF(parm.Status != -1, data => data.Status == parm.Status);

        return await Queryable()
            .LeftJoin<Notice>((key, notice) => key.Nid == notice.Id)
            .LeftJoin<User>((key, notice, getUser) => key.GetUid == getUser.Id)
            .LeftJoin<User>((key, notice, getUser, postUser) => notice.PostUid == postUser.Id)
            .Where(exp.ToExpression())
            .WhereIF(!string.IsNullOrEmpty(parm.Title), (data, notice) => notice.Title.Contains(parm.Title))
            .WhereIF(parm.ListType == 2, (key, notice) => notice.PostUid == parm.Uid)//空或1为收到消息列表,2是已发消息列表
            .WhereIF(parm.ListType != 2, (key, notice) => key.GetUid == parm.Uid)
            .OrderBy((key) => new { Id = SqlFunc.Desc(key.Id), Status = SqlFunc.Asc(key.Status) }, OrderByType.Desc)
            .Select((key, notice, getUser, postUser) => new ViewNotice()
            {
                Id = key.Id,
                GetUid = key.GetUid,
                ReadTime = key.ReadTime,
                Status = key.Status,
                GetNickname = getUser.NickName,
                GetUserAvatar = getUser.Avatar,
                PostNickname = postUser.NickName,
                PostAvatar = postUser.Avatar,
                Title = notice.Title,
                Type = notice.Type,
                PostUid = notice.PostUid,
                PostTime = notice.PostTime,
                NoticeId = notice.Id,
            })
            .ToPageAsync(parm);
    }

    /// <summary>
    /// 批量写入通知 无返回值 
    /// </summary>
    /// <param name="editNotice"></param>
    /// <param name="uid"></param>
    public virtual async Task<bool> InsertByUid(EditNotice editNotice, int uid = 0)
    {
        if (string.IsNullOrEmpty(editNotice.GetUid))
            return false;
        try
        {
            Notice notice = new()
            {
                Title = editNotice.Title,
                PostTime = DateTime.Now,
                PostUid = uid > 0 ? uid : 0,
                Type = uid > 0 ? 1 : 0,
                Content = editNotice.Content,
                Att = editNotice.Att,
            };
            int resNoticeId = await _noticeService.InsertReturnIdAsync(notice);
            List<int> uids = JsonSerializer.Deserialize<List<int>>(editNotice.GetUid);
            //string[] uids = editNotice.GetUid.Split(',');
            // int[] intUids = Array.ConvertAll(uids, int.Parse);
            for (int i = 0; i < uids.Count; i++)
            {
                NoticeKey noticeKey = new()
                {
                    Nid = resNoticeId,
                    GetUid = uids[i],
                    Status = 0,
                };
                await InsertAsync(noticeKey);
            }
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
       
    }
}
